package com.um.jdy.app.charge.scheduled;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.um.jdy.app.charge.manager.EBOrderManager;
import com.um.jdy.app.charge.manager.EBoxOrderManager;
import com.um.jdy.common.charge.entity.po.EbOrder;
import com.um.jdy.common.charge.entity.po.EvOrder;
import com.um.jdy.common.charge.entity.po.Order;
import com.um.jdy.common.charge.enums.OrderEnum;
import com.um.jdy.common.charge.enums.OrderStopReason;
import com.um.jdy.common.charge.service.EbOrderService;
import com.um.jdy.common.charge.service.EvOrderService;
import com.um.jdy.common.charge.service.OrderService;
import com.um.jdy.rpc.enums.DeviceTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author 甘天伟
 * @since 2022/4/23
 * 版权所有 广州优匠科技有限公司
 */
@Slf4j
@Component
public class OrderTask {

    @Autowired
    OrderService orderService;

    @Autowired
    EBOrderManager ebOrderManager;

    @Autowired
    EBoxOrderManager eBoxOrderManager;


    /**
     * 自动停止设备离线、订单超时未结束的订单 600000
     */
    @Async
    @Scheduled(fixedRate = 60000)
    @Profile({"!dev"})
    public void autoStopOrders() {
        log.info("执行自动停止设备离线、订单超时未结束的订单");
        List<Order> orderList = orderService.getListBySqlName("get_timeout_not_stoped_order_list", new Object[]{});
        for (Order order : orderList) {
            String orderNo = order.getOrderNo();
            try {
                switch (DeviceTypeEnum.valueOf(order.getDeviceType())) {
                    case EB:
                        ebOrderManager.cancelPaidOrder(orderNo, OrderStopReason.EB.OFFLINE_SYS_END.name(), true);
                        break;
                    case EBox:
                        eBoxOrderManager.cancelPaidOrder(orderNo,OrderStopReason.EBox.OFFLINE_SYS_END.name(),true);
                        break;
                }
            } catch (Exception ex) {
                log.error(StrUtil.format("自动停止设备离线、订单超时未结束的订单{}出错", orderNo), ex);
            }
        }
        log.info("处理完成{}个订单", orderList.size());
    }

    /**
     * 取消漏网异常订单，每10分钟执行一次（首次为程序启动后60秒）
     */
    @Async
    @Scheduled(fixedRate = 600000, initialDelay = 60000)
    @Profile({"!dev"})
    public void autoCancelOrders() {
        log.info("执行自动取消超时未启动订单任务");
        List<Order> orderList = orderService.getListBySqlName("get_timeout_not_started_order_list", new Object[]{});
        for (Order order : orderList) {
            String orderNo = order.getOrderNo();
            try {
                switch (DeviceTypeEnum.valueOf(order.getDeviceType())) {
                    case EB:
                        ebOrderManager.cancelPaidOrder(orderNo, OrderStopReason.EB.PLATFORM_CANCEL.name(), true);
                        break;
                    case EBox:
                        eBoxOrderManager.cancelPaidOrder(orderNo,OrderStopReason.EBox.PLATFORM_CANCEL.name(),true);
                        break;
                }
            } catch (Exception ex) {
                log.error(StrUtil.format("自动取消未启动订单{}出错", orderNo), ex);
            }
        }
        log.info("处理完成{}个订单", orderList.size());

    }

    /**
     * 取消漏网异常订单，每10分钟执行一次（首次为程序启动后60秒）
     */
    @Async
    @Scheduled(fixedRate = 600000, initialDelay = 60000)
    @Profile({"!dev"})
    public void autoCancelUnpaidOrders() {
        log.info("执行自动取消超时未支付订单任务");
        List<Order> orderList = orderService.getListBySqlName("get_timeout_unpaid_order_list", new Object[]{});
        for (Order order : orderList) {
            String orderNo = order.getOrderNo();
            try {
                switch (DeviceTypeEnum.valueOf(order.getDeviceType())) {
                    case EB:
                        ebOrderManager.cancelUnpaidOrder(orderNo);
                        break;
                }
            } catch (Exception ex) {
                log.error(StrUtil.format("自动取消超时未支付订单{}出错", orderNo), ex);
            }
        }
        log.info("处理完成{}个订单", orderList.size());
    }


    /**
     * TODO 修复数据， 下个版本删除
     */
//     @Autowired
//     EvOrderService evOrderService;
//     @Autowired
//     EbOrderService ebOrderService;
//     @Scheduled(fixedDelay = Long.MAX_VALUE)
//     public void fixOrderChargeCapacity() {
//         List<Order> all = orderService.getRows(new String[]{}, new String[]{});
//         for (Order order : all) {
//             if(order.getEnergyFee() > 0){
//                 continue;
//             }
//
//             Order update = new Order();
//             update.setChargeOrderId(order.getChargeOrderId());
//
//             if(DeviceTypeEnum.EV.name().equals(order.getDeviceType())){
//                 EvOrder subOrder = evOrderService.getRow("charge_order_id", order.getChargeOrderId());
//                 if(null != subOrder){
//                     update.setEnergyFee(order.getChargeAmount());
//                     update.setServiceFee(subOrder.getServiceAmount());
//                 }
//             }else if(DeviceTypeEnum.EB.name().equals(order.getDeviceType())){
//                 EbOrder subOrder = ebOrderService.getRow("charge_order_id", order.getChargeOrderId());
//                 if(null != subOrder){
//                     update.setEnergyFee(subOrder.getEnergyFee());
//                     update.setServiceFee(subOrder.getServiceFee());
//                 }
//             }
//             if(orderService.saveRow(update)){
//                 log.info("修复订单电费+服务费: {}", JSONUtil.toJsonStr(update));
//             }
//         }
//
//     }

}
